// 导入创建切片的方法
import { createSlice } from '@reduxjs/toolkit'

// 创建一个切片
const appSlice = createSlice({
    name: 'user', // 定义切片名称
    initialState: {
        loginState: localStorage.getItem('loginState') == 'true',
        adminname: localStorage.getItem('adminname') || '',
        checkedkeys: JSON.parse(localStorage.getItem('checkedkeys')) || [],
        role: localStorage.getItem('role') * 1 || 1,
        token: localStorage.getItem('token') || ''
    },
    reducers: {
        changeUser(state, actions) {
            state.adminname = actions.payload.adminname
            state.checkedkeys = actions.payload.checkedkeys
            state.loginState = actions.payload.loginState
            state.role = actions.payload.role
            state.token = actions.payload.token

            // 将用户的登录信息保存在本地，防止刷新页面的时候数据丢失
            localStorage.setItem('adminname', actions.payload.adminname)
            localStorage.setItem('checkedkeys', JSON.stringify(actions.payload.checkedkeys))
            localStorage.setItem('loginState', actions.payload.loginState)
            localStorage.setItem('role', actions.payload.role)
            localStorage.setItem('token', actions.payload.token)

        }
    }
})
// 导出修改方法
export const { changeUser } = appSlice.actions

// 导出 reducer
export default appSlice.reducer